package elastic

import (
	"context"
	"github.com/olivere/elastic/v7"
)

/**
@desc consul配置项
@host 指consul服务的host
@port 指consul服务的port
*/

type Elastic struct {
	Host string
	Port int
}

type ElasticClient interface {
	CreateData(data interface{}, index string) *elastic.IndexResponse //新增索引
	GetDataByID(index string, id string) *elastic.GetResult           //通过索引值和ID查询单条数据
	QueryAll(index string, size int, page int, keyWord string) *elastic.SearchResult
}

func NewElasticClient(host string, port int) ElasticClient {
	return &Elastic{
		Host: host,
		Port: port,
	}
}

/**
@author fuyx
@date 2041/08/28
@desc
*/

func (elastics *Elastic) CreateData(data interface{}, index string) *elastic.IndexResponse {
	//client, err := elastic.NewClient(elastic.SetURL(fmt.Sprintf("http://%s:%d", elastics.Host, elastics.Port)))
	client, err := elastic.NewClient(elastic.SetSniff(false), elastic.SetURL("http://121.36.211.57:9200/"))
	if err != nil {
		// Handle error
		panic(err)
	}
	result, err := client.Index().
		Index(index).
		BodyJson(data).
		Do(context.Background())
	if err != nil {
		panic(err)
	}
	return result
}

func (elastics *Elastic) GetDataByID(index string, id string) *elastic.GetResult {
	client, err := elastic.NewClient(elastic.SetSniff(false), elastic.SetURL("http://121.36.211.57:9200/"))
	if err != nil {
		// Handle error
		panic(err)
	}
	result, err := client.Get().
		Index(index).
		Id(id).
		Do(context.Background())
	if err != nil {
		panic(err)
	}
	return result
}

func (elastics *Elastic) QueryAll(index string, size int, page int, keyWord string) *elastic.SearchResult {
	client, err := elastic.NewClient(elastic.SetSniff(false), elastic.SetURL("http://121.36.211.57:9200/"))
	if err != nil {
		// Handle error
		panic(err)
	}
	result, err := client.Search(index).
		Size(size).
		From((page - 1) * size).
		Query(elastic.NewMatchQuery("Name", keyWord)).
		Highlight(elastic.NewHighlight().
			Field("Name").
			PreTags("<em>").
			PostTags("</em>")).
		Do(context.Background())
	return result
}
